<?php
use Workerman\Worker;
require_once __DIR__ . '/Workerman/Autoloader.php';

// 注意：这里与上个例子不同，使用的是websocket协议
$ws_worker = new Worker("websocket://0.0.0.0:8246");

// 启动4个进程对外提供服务
$ws_worker->count = 1;

// 在线人数
$user_count = 0;

// 用列表
$users = array();

$ws_worker->onConnect = function($connection)
{
    global $ws_worker,$user_count;

    $user_count++;

    foreach($ws_worker->connections as $con){
        $str = json_encode(array(
            'action_type' => 'user_count',
            'user_count' => $user_count
        ));

        $con->send($str);
    }
};

$ws_worker->onClose = function($connection)
{
    global $ws_worker,$user_count,$users;

    $user_count--;

    foreach($users as $key => $value){
        if($connection->uid == $value['uid']){
            unset($users[$key]);
        }
    }

    foreach($ws_worker->connections as $con){
        $str = json_encode(array(
            'action_type' => 'user_close',
            'user_count' => $user_count,
            'users' => $users
        ));

        $con->send($str);
    }
};

// 当收到客户端发来的数据后返回hello $data给客户端
$ws_worker->onMessage = function($connection, $data)
{
    // 声明全局变量
    global $ws_worker,$user_count,$users;
    // 先转义成数组处理
    $data_arr = json_decode($data, true);
    // 判断消息类型
    if($data_arr['action_type'] == 'login'){
        file_put_contents("cs.txt", date('Y-m-d H:i:s', time()) . ': 登录' . PHP_EOL, FILE_APPEND);
        // 设置连接的用户信息
        $connection->uid = $data_arr['uid'];
        $connection->username = $data_arr['username'];

        $users[] = array(
            'uid' => $connection->uid,
            'username' => $connection->username
        );
        $str = $data_arr['username'].'已经进入了聊天室';
        $str = json_encode(array(
            'action_type' => 'new_user',
            'username' => $data_arr['username'],
            'text' => '进入了聊天室',
            'users' => $users
        ));
        // 遍历当前进程所有的客户端连接，发送某某进入了聊天室的信息
        foreach($ws_worker->connections as $con)
        {
            // 给所有连接发送信息
            $con->send($str);
        }
    }else if($data_arr['action_type'] == 'send_msg'){
        file_put_contents("cs.txt", date('Y-m-d H:i:s', time()) . ' : ' . $data_arr['username'] . ' : ' . $data_arr['content'] . PHP_EOL, FILE_APPEND);
        foreach($ws_worker->connections as $con)
        {
            if($connection->uid == $con->uid){
                $is_my = 1;
            }else{
                $is_my = 0;
            }
            $json_str = json_encode(array(
                'action_type' => 'new_msg',
                'is_my' => $is_my,
                'uid' => $connection->uid,
                'uids' => $con->uid,
                'username' => $connection->username,
                'content' => $data_arr['content']
            ));
            // 给所有连接发送信息
            $con->send($json_str);
        }
    }
};

// 运行worker
Worker::runAll();